package com.menghao.rpc.netty.in;

import com.menghao.rpc.netty.TcpMessageHandler;
import com.menghao.rpc.netty.model.TcpConnection;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;

/**
 * <p>Netty上行处理Handler.</br>
 * <p>该层已经可以获取到反序列化后的对象</p>
 * <p>根据对象为 RpcRequest、RpcResponse，执行不同的处理逻辑</p>
 *
 * @author MarvelCode
 */
public class TcpInboundHandler extends SimpleChannelInboundHandler<Object> {

    private List<TcpMessageHandler> messageHandlers;

    public TcpInboundHandler(List<TcpMessageHandler> messageHandlers) {
        this.messageHandlers = messageHandlers;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
        if (o == null) {
            return;
        }
        for (TcpMessageHandler tcpMessageHandler : messageHandlers) {
            Channel channel = channelHandlerContext.channel();
            if (tcpMessageHandler.support(o.getClass())) {
                tcpMessageHandler.handler(new TcpConnection(channel), o);
            }
        }
    }
}
